//
//  HOTCloseDownSubListViewController.m
//  Genpara
//
//  Created by AndyChang.zhang on 14-9-9.
//  Copyright (c) 2014年 zhangchh. All rights reserved.
//

#import "HOTCloseDownSubListViewController.h"
#import "HOTCloseDownSubCell.h"
#import "ZZZNSString+Extend.h"
#import "HOTCloseDownDetailListViewController.h"
#import "MJRefreshBaseView.h"
#import "MJRefresh.h"
#import "HOTCostPopupHandler.H"
#import "HOTNavigationViewController.h"
#import "HOTEntryViewController.h"

@interface HOTCloseDownSubListViewController () <UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, HOTEntryViewControllerDelegate> {
    
    NSMutableArray *_dataList;
    BOOL isRegisted;
    NSString *_selDate;
    NSMutableDictionary *_parameters;
    NSInteger _pageNo;
    UIView *mengBan;
    HOTNavigationViewController *nav_;
}

@property(nonatomic,strong)NSMutableArray *dataList;

@end

@implementation HOTCloseDownSubListViewController

@synthesize dataList = _dataList;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil selDate:(NSString *)selDate
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _selDate = selDate;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setNaviTitle:@"俺の現場がヤバい！" fontSize:20 fontName:HOTTitleFont_ROUNDED_X];
    
    _tableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_bankruptcy"]];
    
    _tableView.showFooter = YES;
    _tableView.showHeader = YES;
    
    __unsafe_unretained HOTCloseDownSubListViewController *tempObj = self;
    _tableView.headerView.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        _pageNo = 1;
        [tempObj requestDataFromNet];
    };
    
    //_searchBarView.frame = CGRectMake(0, -_searchBarView.frame.size.height, self.view.frame.size.width, _searchBarView.frame.size.height);
    
    mengBan = [[UIView alloc] initWithFrame:CGRectMake(0, _searchBarView.frame.size.height, self.view.frame.size.width, self.view.frame.size.height)];
    mengBan.backgroundColor = [UIColor blackColor];
    
    //[self.view addSubview:_searchBarView];
    _searchBarView.delegate = self;
    _tableView.footerView.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        _pageNo ++;
        [tempObj requestDataFromNet];
    };

    _parameters = [[NSMutableDictionary alloc] init];
    self.dataList = [[NSMutableArray alloc] initWithCapacity:10];
    
    //添加导航右侧搜索按钮
    [self addRightBtnTarget:self
                     action:@selector(searchBtnClicked:)
                      image:[UIImage imageNamed:@"btn_search_off"]
                     hImage:[UIImage imageNamed:@"btn_search_on"]];
    
    _pageNo ++;
    [self requestDataFromNet];
}

-(void)requestDataFromNet {
    
    [self showLoading];
    
    NSDictionary *parameters = @{REQ_KEY_USER_TOKEN:self.userInfo.token,
                                 REQ_KEY_QUERY_TIME:_selDate,
                                 REQ_KEY_QUERY_WORD:[HOTUtils getString:self.freeWord],
                                 REQ_KEY_P_NUM:@(_pageNo),
                                 REQ_KEY_P_SIZE:kPageCnt};
    
    __unsafe_unretained HOTCloseDownSubListViewController *tempObj = self;
    [self requestWithURL:HOT_URL_CLOSURE_DATE_LIST Parameters:parameters success:^(NSInteger result, NSArray * dataArr) {
        
        [tempObj loadingSuccess];
        [_tableView.headerView endRefreshing];
        [_tableView.footerView endRefreshing];
        if (dataArr.count == 0) {
            
            if (_pageNo == 1) {
                
                [tempObj.dataList removeAllObjects];
                [_tableView reloadData];
                [self alertNoDataMessage:^{
                    //[tempObj.navigationController popViewControllerAnimated:YES];
                }];
            } else {
                [self alertNoDataAgainMessage:nil];
            }
            
            
            return;
        }

        if (_pageNo == 1) {
            [tempObj.dataList removeAllObjects];
        }
        [tempObj.dataList addObjectsFromArray:dataArr];
        
        [_tableView reloadData];
        
    } failure:^(NSError *error, NSString *errMsg) {
        
        [tempObj loadingSuccess];
        [_tableView.headerView endRefreshing];
        [_tableView.footerView endRefreshing];
        
        if ([tempObj checkErrResult:error errMsg:errMsg]) {
            return ;
        }
        
        if (errMsg.length > 0) {
            
            ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                                  message:errMsg
                                                                 delegate:nil
                                                        cancelButtonTitle:nil
                                                         otherButtonTitle:ALERT_BTN_OK];
            
            [popupView showInWindow];
        }
    }];
}

#pragma mark - UItableView DataSource
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellId = @"cellID";
    HOTCloseDownSubCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if (cell == nil) {
        
        UINib *nib = [UINib nibWithNibName:XIB(@"HOTCloseDownSubCell") bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:cellId];
        cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        cell.selectedBackgroundView = nil;
        
    }
    
    NSDictionary *dic = [self.dataList objectAtIndex:indexPath.row];
    NSString *title = [dic objectForKey:@"company_name"];
    NSString *count = [dic objectForKey:@"comment_sum"];
    
    cell.contentLabel.text = title;
    cell.countLabel.text = [NSString stringWithFormat:@"（%@）", [count toStr]];
    
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataList.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 52;
}

#pragma mark - UITableView Delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *dic = [self.dataList objectAtIndex:indexPath.row];
    __block NSString *title = [dic objectForKey:@"company_name"];
    NSString *cId = [dic objectForKey:@"company_id"];
    
    __unsafe_unretained HOTCloseDownSubListViewController *tempObj = self;
    
    if ([HOTConfig config].isFree) {
        
        HOTCloseDownDetailListViewController *hcddlvc = [[HOTCloseDownDetailListViewController alloc] initWithNibName:@"HOTCloseDownDetailListViewController" bundle:nil compenyId:cId];
        hcddlvc.selDate = _selDate;
        [hcddlvc setNaviTitle:title];
        [tempObj.navigationController pushViewController:hcddlvc animated:YES];
        
    } else {
        if ([self userAuthorized]) {
            
            [[HOTCostPopupHandler costPopupHandler] showWithPopupStyle:HOTCostPopupStyle3
                                                              userInfo:@{@"title":title}
                                                                cancel:nil
                                                               confirm:^{
                                                                   
                                                                HOTCloseDownDetailListViewController *hcddlvc = [[HOTCloseDownDetailListViewController alloc] initWithNibName:@"HOTCloseDownDetailListViewController" bundle:nil compenyId:cId];
                                                                   hcddlvc.selDate = _selDate;
                                                                   [hcddlvc setNaviTitle:title];
                                                                   [tempObj.navigationController pushViewController:hcddlvc animated:YES];
                                                               }];
        }
        
    }
    
    
    //NSString *count = [dic objectForKey:@"count"];
}

#pragma mark - UISearchBar Delegate
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    
    [_searchBarView setShowsCancelButton:NO animated:YES];
    [self hiddenMengban];
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
    //按关键字搜索
    self.freeWord = _searchBarView.text;
    [self searchBtnClicked:nil];

}

-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    
    [self showMengban];
    
    return YES;
}

#pragma mark - 私有函数
-(void)searchBtnClicked:(id)sender {

    if ([_searchBarView isFirstResponder]) {

        [_searchBarView setShowsCancelButton:NO animated:YES];
        [self hiddenMengban];
    }
    self.freeWord = _searchBarView.text;
    [self requestDataFromNet];
}

-(void)showMengban {
    
    //[_searchBarView becomeFirstResponder];
    mengBan.alpha = 0;
    [self.view addSubview:mengBan];
    [_searchBarView setShowsCancelButton:YES animated:YES];
    [UIView animateWithDuration:0.3 animations:^{
        
        //_searchBarView.frame = CGRectMake(0, 0, self.view.frame.size.width, _searchBarView.frame.size.height);
        mengBan.alpha = 0.7f;
        
    } completion:^(BOOL finished) {
//        if (finished) {
//            [_searchBarView becomeFirstResponder];
//        }
        
    }];
}

-(void)hiddenMengban {
    
    [_searchBarView resignFirstResponder];
    [UIView animateWithDuration:0.3 animations:^{
        
        mengBan.alpha = 0.f;
        //_searchBarView.frame = CGRectMake(0, -_searchBarView.frame.size.height, self.view.frame.size.width, _searchBarView.frame.size.height);
        
    } completion:^(BOOL finished) {
        
        if (finished) {
            //[_searchBarView resignFirstResponder];
            [mengBan removeFromSuperview];
            //[_searchBarView removeFromSuperview];
        }
    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)userAuthorized
{
    HOTUserInfo *userInfo = [HOTUserInfo defaultUser];
    
    if ([userInfo isLogined]) {
        return YES;
    } else {
        HOTEntryViewController *entryVC = [[HOTEntryViewController alloc] initWithNibName:@"HOTEntryViewController" bundle:nil];
        entryVC.delegate = self;
        [entryVC setNaviTitle:@"入場"];
        nav_ = [HOTNavigationViewController createNaviWithRootViewController:entryVC];
        [self presentViewController:nav_ animated:YES completion:nil];
        return NO;
    }
    return YES;
}

#pragma mark - HOTEntryViewControllerDelegate

- (void)entrySuccessed
{
    [nav_ dismissViewControllerAnimated:YES completion:nil];
}

@end
